<template>
  <div class="categories-management">
    <el-card class="mb-4">
      <el-form :model="categoryQuery" inline ref="categoryQueryRef">
        <el-form-item prop="name">
          <el-input v-model="categoryQuery.name" placeholder="搜索分类名称" prefix-icon="Search" clearable></el-input>
        </el-form-item>
        <el-form-item prop="level">
          <el-select v-model="categoryQuery.level" placeholder="选择层级" clearable style="width: 240px">
            <el-option label="全部" value=""></el-option>
            <el-option label="一级分类" value="1"></el-option>
            <el-option label="二级分类" value="2"></el-option>
            <el-option label="三级分类" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchCategories">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="default" @click="resetFilters(categoryQueryRef)">
            重置
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Plus" @click="handleAdd">
            新增分类
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 数据表格 -->
    <el-card>
      <el-table
          :data="categoryPage.list"
          border
          stripe
          v-loading="loading"
          element-loading-text="加载中..."
          style="width: 100%"
      >
        <el-table-column prop="categoryId" label="ID" align="center"></el-table-column>
        <el-table-column label="图标" align="center">
          <template #default="scope">
            <el-image
                :src="scope.row.icon"
                :preview-src-list="[scope.row.icon]"
                style="width: 40px; height: 40px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="分类名称" align="center" prop="name"></el-table-column>
        <el-table-column label="层级" align="center" width="100">
          <template #default="scope">
            <el-tag
                :type="scope.row.level === 1 ? 'primary' :
                      scope.row.level === 2 ? 'success' : 'warning'"
            >
              {{ scope.row.level }}级分类
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
            label="父分类"
            align="center"
        >
          <template #default="scope">
            {{ getParentCategoryName(scope.row.parentId) || '-' }}
          </template>
        </el-table-column>
        <el-table-column
            prop="sortOrder"
            label="排序"
            align="center"
            width="80"
        ></el-table-column>
        <el-table-column
            label="推荐"
            align="center"
            width="100"
        >
          <template #default="scope">
            <el-text>{{ scope.row.isFeatured }}</el-text>
          </template>
        </el-table-column>
        <el-table-column
            prop="createdAt"
            label="创建时间"
            align="center"
            width="180"
        >
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            align="center"
            width="180"
        >
          <template #default="scope">
            <el-button
                size="small"
                text
                @click="handleView(scope.row)"
            >
              查看
            </el-button>
            <el-button
                size="small"
                text
                type="primary"
                @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
                size="small"
                text
                type="danger"
                @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container mt-4">
        <el-pagination
            v-model:current-page="categoryQuery.pageNum"
            v-model:page-size="categoryQuery.pageSize"
            :page-sizes="[10, 20, 50]"
            :total="categoryPage.total"
            layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 新增/编辑分类弹窗 -->
    <el-dialog
        v-model="showModal"
        :title="isEditing ? '编辑分类' : '新增分类'"
        width="600"
        :before-close="handleDialogClose"
    >
      <el-form ref="categoryForm" :model="formData" :rules="formRules" label-width="100px" class="mt-2">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input
              v-model="formData.description"
              placeholder="请输入分类描述"
              type="textarea"
              :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item label="父分类" prop="parentId">
          <el-cascader v-model="formData.parentId" :options="parentsTree" :props="props" />
        </el-form-item>
        <el-form-item label="分类层级" prop="level">
          <el-select v-model="formData.level" placeholder="请选择分类层级">
            <el-option label="一级分类" :value="1"></el-option>
            <el-option label="二级分类" :value="2"></el-option>
            <el-option label="三级分类" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序权重" prop="sortOrder">
          <el-input-number
              v-model="formData.sortOrder"
              :min="0"
              :step="1"
              placeholder="请输入排序权重"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="是否推荐" prop="isFeatured">
          <el-switch
              v-model="formData.isFeatured"
              :active-value="1"
              :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item label="封面图">
          <el-upload
              v-model:file-list="formData.coverFileList"
              :action="fileUpload"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              list-type="picture"
              :limit="1"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip text-xs">
                只能上传jpg/png文件，且不超过2MB
              </div>
            </template>
          </el-upload>
          <el-image
              v-if="formData.cover && formData.coverFileList.length === 0"
              :src="formData.cover"
              style="width: 100px; height: 100px; margin-top: 10px"
              :preview-src-list="[formData.cover]"
          ></el-image>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="submitCategory(categoryForm)">确认</el-button>
      </template>
    </el-dialog>

    <!-- 查看分类详情弹窗 -->
    <el-dialog
        v-model="showViewDialog"
        title="分类详情"
        width="50%"
        :before-close="handleViewDialogClose"
    >
      <el-descriptions column="1" border>
        <el-descriptions-item label="ID">{{ viewData.categoryId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="分类名称">{{ viewData.name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="分类描述">{{ viewData.description || '-' }}</el-descriptions-item>
        <el-descriptions-item label="父分类">{{
            getParentCategoryName(viewData.parentId) || '-'
          }}
        </el-descriptions-item>
        <el-descriptions-item label="分类层级">{{
            viewData.level ? `${viewData.level}级分类` : '-'
          }}
        </el-descriptions-item>
        <el-descriptions-item label="排序权重">{{ viewData.sortOrder || '-' }}</el-descriptions-item>
        <el-descriptions-item label="是否推荐">{{ viewData.isFeatured === 1 ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="封面图">
          <el-image
              v-if="viewData.cover"
              :src="viewData.cover"
              style="width: 200px; height: 200px"
              :preview-src-list="[viewData.cover]"
          ></el-image>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(viewData.createdAt) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(viewData.updatedAt) || '-' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="handleViewDialogClose">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
        v-model="showDeleteDialog"
        title="确认删除"
        width="30%"
        :before-close="handleDeleteDialogClose"
    >
      <p>确定要删除分类 <span class="text-primary">{{ deleteData.name }}</span> 吗？</p>
      <p class="text-danger text-sm mt-2">提示：删除后数据将无法恢复，请谨慎操作！</p>

      <template #footer>
        <el-button @click="handleDeleteDialogClose">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确认删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, computed, onMounted, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import type {FormInstance} from 'element-plus'
import {formatDate,fileUpload} from '@/util';
import {reqAddCategory, reqGetCategoryPage, reqGetCategoryParentsTree, reqUpdateCategory} from "@/api/share/category";

const loading = ref(true);
let categoryForm=ref()
let categoryQueryRef = ref(null);
let categoryQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  level: '',
  parentId: '',
});
let props = reactive({
  value:'categoryId',
  label:'name',
  children:'children',
  checkStrictly:true,
  emitPath:false
});
const isEditable = ref(true);

// 弹窗状态
const showModal = ref(false);
const showViewDialog = ref(false);
const showDeleteDialog = ref(false);
const isEditing = ref(false);

// 表单数据
const formData = reactive({
  categoryId: null,
  name: '',
  description: '',
  parentId: null,
  level: 1,
  sortOrder: 0,
  isFeatured: 0,
  cover: '',
  coverFileList: []
});
let parentsTree = ref([]);
let categoryPage = reactive({
  pageNum: 1,
  total: 0,
  list: []
})

// 查看数据
const viewData = ref({});
// 删除数据
const deleteData = ref({});

// 表单验证规则
const formRules = reactive({
  name: [
    {required: true, message: '请输入分类名称', trigger: 'blur'},
    {min: 2, max: 50, message: '分类名称长度在 2 到 50 个字符', trigger: 'blur'}
  ],
  level: [
    {required: true, message: '请选择分类层级', trigger: 'change'}
  ],
  sortOrder: [
    {required: true, message: '请输入排序权重', trigger: 'blur'}
  ]
});
// 生命周期钩子
onMounted(() => {
  fetchCategories();
  getParentsTree()
});

watch([()=>categoryQuery.pageNum, ()=>categoryQuery.pageSize],()=>{
  fetchCategories()
})

let getParentsTree = async () => {
  let res = await reqGetCategoryParentsTree()
  parentsTree.value = res.data
}
// 方法 - 获取所有分类
const fetchCategories = async () => {
  loading.value = true;
  try {
    let res = await reqGetCategoryPage(categoryQuery)
    Object.assign(categoryPage, res.data)
  } catch (error) {
    console.error('加载分类失败:', error);
  } finally {
    loading.value = false;
  }
};

const getParentCategoryName = (parentId) => {
  if (!parentId) return null;
  const parent = categoryPage.list.find(item => item.categoryId === parentId);
  return parent ? parent.name : null;
};


// 方法 - 重置筛选条件
const resetFilters = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 方法 - 新增分类
const handleAdd = () => {
  resetForm();
  isEditing.value = false;
  showModal.value = true;
};

// 方法 - 编辑分类
const handleEdit = (category) => {
  resetForm();
  isEditing.value = true;
  // 填充表单数据
  formData.categoryId = category.categoryId;
  formData.name = category.name;
  formData.description = category.description;
  formData.parentId = category.parentId;
  formData.level = category.level;
  formData.sortOrder = category.sortOrder;
  formData.isFeatured = category.isFeatured;
  formData.cover = category.cover;

  // 如果有封面图，添加到文件列表预览
  if (formData.cover) {
    formData.coverFileList = [
      {
        name: `cover-${category.categoryId}`,
        url: formData.cover
      }
    ];
  }

  showModal.value = true;
};

// 方法 - 查看分类
const handleView = (category) => {
  viewData.value = {...category};
  showViewDialog.value = true;
};

// 方法 - 删除分类（确认前）
const handleDelete = (category) => {
  deleteData.value = {...category};
  showDeleteDialog.value = true;
};

// 方法 - 确认删除
const confirmDelete = async () => {
  try {
    showDeleteDialog.value = false;
  } catch (error) {
    console.error('删除分类失败:', error);
    ElMessage.error('删除分类失败，请重试');
  }
};

// 方法 - 提交分类表单
const submitCategory = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        if (isEditing.value) {
          await fetchCategories()
        } else {
          await reqAddCategory(formData)
        }
        await reqUpdateCategory(formData)
        showModal.value = false;
      } catch (error) {
        console.error(isEditing.value ? '更新分类失败:' : '新增分类失败:', error);
        ElMessage.error(`${isEditing.value ? '更新' : '新增'}分类失败，请重试`);
      }
    } else {
      console.log('error submit!', fields)
    }
  })
};

// 方法 - 重置表单
const resetForm = () => {
  formData.categoryId = null;
  formData.name = '';
  formData.description = '';
  formData.parentId = null;
  formData.level = 1;
  formData.sortOrder = 0;
  formData.isFeatured = 0;
  formData.cover = '';
  formData.coverFileList = [];
};

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    ElMessage.error('只能上传JPG/PNG格式的图片');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB');
    return false;
  }
  return true;
};

const handleUploadSuccess = (response, uploadFile) => {
  // 假设上传成功后返回图片URL
  formData.cover = response.data.visitPath;
  ElMessage.success('图片上传成功');
};

// 弹窗关闭相关方法
const handleDialogClose = () => {
  showModal.value = false;
  resetForm();
};

const handleViewDialogClose = () => {
  showViewDialog.value = false;
  viewData.value = {};
};

const handleDeleteDialogClose = () => {
  showDeleteDialog.value = false;
  deleteData.value = {};
};
</script>

<style scoped>
.pagination-container {
  text-align: right;
}

::v-deep .el-upload-list {
  margin-top: 10px;
}
</style>
